package common

import (
	"bytes"
	"core/ini"
	"encoding/json"
	"io"
	"net/http"
	"strconv"
	"time"
)

func SendCenterHttpRequest(req interface{}, response interface{}, method, url string) error {
	httpClient := &http.Client{Timeout: 500 * time.Millisecond}
	bytesData, _ := json.Marshal(req)
	request, err := http.NewRequest(method, "http://localhost"+":"+strconv.Itoa(ini.CfgGetMe().Server.CenterHttpPort)+
		url, bytes.NewReader(bytesData))
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err := httpClient.Do(request)
	if err != nil {
		return err
	}
	rsp := &HttpResponse{}
	body, _ := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	err = json.Unmarshal(body, rsp)
	if err != nil {
		return err
	}
	_ = json.Unmarshal(rsp.Data, &response)
	return nil
}

func SendOnlineHttpRequest(req interface{}, response interface{}, url string, httpPort int) error {
	httpClient := &http.Client{Timeout: 500 * time.Millisecond}
	bytesData, _ := json.Marshal(req)
	request, err := http.NewRequest("POST", "http://localhost"+":"+strconv.Itoa(httpPort)+url, bytes.NewReader(bytesData))
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err := httpClient.Do(request)
	if err != nil {
		return err
	}
	rsp := &HttpResponse{}
	body, _ := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	err = json.Unmarshal(body, rsp)
	if err != nil {
		return err
	}
	_ = json.Unmarshal(rsp.Data, &response)
	return nil
}
